<template>
  <el-container>
    <el-main class="main">
      <!--      第一行数据检索包括省区数据检索 市区数据检索 站点数据检索 数据导出-->
      <!--      数据检索包括 站点名 时间段 -->
      <el-form class="form" ref="searchForm" :model="searchList" :inline="true" label-width="80px">
        <el-form-item required label="数据范围" prop="range">
          <el-select @change="handleRangeChange" v-model="searchList.range" placeholder="请选择数据范围">
            <el-option v-for="item in rangeList" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="数据ID" prop="id">
          <el-select-v2 v-model="searchList.id" placeholder="请输入数据ID" :options="idList"/>
        </el-form-item>
        <el-form-item required label="时间范围" prop="timeRange">
          <el-date-picker v-model="searchList.timeRange" placeholder="请选择时间范围"
                          value-format="YYYY-MM-DDTHH:mm:ss"
                          type="datetimerange"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="search" icon="Search">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" size="mini" @click="handleExport" icon="Download">导出</el-button>
        </el-form-item>
      </el-form>
      <VueDraggable class="width-100" v-model="dataList" animation="150" target="tbody">
        <el-table table-layout="auto" fit :data="dataList">
          <el-table-column min-width="100" v-for="item in Object.keys(dataList.length>0?dataList[0]:[])" :prop="item"
                           :label="item"></el-table-column>
        </el-table>
      </VueDraggable>
      <el-pagination
          v-if="page.total"
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :page-sizes="[10, 20, 30, 40,50]"
          layout="total,sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :total="page.total"
      />
    </el-main>
  </el-container>
</template>
<script setup lang="ts">
import {onBeforeMount, ref} from "vue";
import {FormInstance} from "element-plus";
import {PageParams} from "@/api/common.ts";
import {exportHistory, getStation, searchHistory} from "@/api/airQuality.ts";
import {getProvinces} from "@/api/province.ts";
import {getAreas} from "@/api/area.ts";
import {VueDraggable} from "vue-draggable-plus";

interface Option {
  value: string;
  label: string
  disabled: boolean;
}

onBeforeMount(() => {
  init()
})

const init = () => {
  initProvince()
}

const initProvince = () => {
  getProvinces().then(res => {
    provinces.push(...res.data.data.map(item => {
      return {
        label: item.provinceName,
        value: String(item.id),
        disabled: false
      }
    }))
  }).then(() => {
    initArea()
    initStation()
  })
}

const initArea = () => {
  getAreas().then(res => {
    areas.push(...res.data.data.map(item => {
      return {
        label: item.cityName,
        value: String(item.cityCode),
        disabled: false
      }
    }))
  })
}

const initStation = () => {
  getStation().then(res => {
    stations.push(...res.data.data.map(item => {
      return {
        label: item.positionName,
        value: item.stationCode,
        disabled: !item.status
      }
    }))
  })
}

const provinces: Option[] = []

const areas: Option[] = []

const stations: Option[] = []

const searchList = ref({
  range: null,
  id: null,
  timeRange: null
})


const page = ref<PageParams>({
  current: 1, size: 20, total: 0
})

const searchForm = ref<FormInstance>()

const rangeList = ref([
  {
    value: 0,
    label: "省区"
  },
  {
    value: 1,
    label: "市区"
  },
  {
    value: 2,
    label: "站点"
  }
])

const idList = ref<Option[]>([])

const dataList = ref([])

const search = () => {
  searchForm.value.validate((valid) => {
    if (valid) {
      // 执行搜索操作
      searchHistory({
        currentPage: page.value.current,
        id: searchList.value.id,
        pageSize: page.value.size,
        range: searchList.value.range,
        timeRange: searchList.value.timeRange
      }).then(res => {
        page.value.total = res.data.data.total
        dataList.value = res.data.data.records
      })
    }
  })
}

const handleRangeChange = async (value: number) => {
  switch (value) {
    case 0: {
      idList.value = provinces
      break
    }
    case 1: {
      idList.value = areas
      break
    }
    case 2: {
      idList.value = stations
      break
    }
  }
  page.value.current = 1
  searchList.value.id = null
}

const handleSizeChange = () => {
  search()
}

const handleCurrentChange = () => {
  search()
}

const handleExport = () => {
  searchForm.value.validate((valid) => {
    if (valid) {
      exportHistory({
        id: searchList.value.id,
        range: searchList.value.range,
        timeRange: searchList.value.timeRange
      }).then(res => {
        handleDownload(res)
      })
    }
  })
}

const handleDownload = (res) => {
  const str = res.headers["content-disposition"]
  let fileName = str.split("filename=").pop()
  let blob = new Blob([res.data], {type: res.headers["Content-Type"]})
  if ('msSaveOrOpenBlob' in navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = window.URL.createObjectURL(blob);
    elink.click();
  }
}
</script>
<style scoped>
.el-form-item__content > .el-select {
  width: 170px;
}

.el-form-item__content > .el-input {
  width: 170px;
}

.el-form-item__content > .el-date-editor {
  width: 240px !important;
}

.el-form {
  text-align: start;
}
</style>
